package cc.lj.internal.core.exception;

import cc.lj.internal.core.http.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 异常拦截器，作用是强制Controller统一返回HttpResult类型数据
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 ServiceException 异常
     */
    @ResponseBody
    @ExceptionHandler(value = ServiceException.class)
    public HttpResult serviceExceptionHandler(HttpServletRequest req, ServiceException ex) {
        log.error(ex.getMessage());
        // 包装 HttpResult 结果
        return HttpResult.error(ex.getCode(), ex.getMessage(),ex.getErrorDetail());
    }

    /**
     * 处理 MissingServletRequestParameterException 异常
     *
     * SpringMVC 参数不正确
     */
    @ResponseBody
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public HttpResult missingServletRequestParameterExceptionHandler(HttpServletRequest req, MissingServletRequestParameterException ex) {
        log.error(ex.getMessage());
        // 包装 HttpResult 结果
        return HttpResult.error(SysExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getCode(), ex.getMessage(),"");
    }

    /**
     * 处理其它 Exception 异常
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public HttpResult exceptionHandler(HttpServletRequest req, Exception e) {
        e.printStackTrace();
        // 记录异常日志
        log.error(e.getMessage());
        // 返回 ERROR HttpResult
        return HttpResult.error(SysExceptionEnum.SYS_ERROR.getCode(),e.getMessage(),"");
    }

    /**
     * 处理POST请求参数校验异常,
     * 因为post RequestBody 接收参数中使用Validate 的时候捕获的异常有很多无用信息，所以这里需要单独处理
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public HttpResult<Map<String,Object>> validExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String, Object> errorMap = fieldErrors.stream()
                .collect(Collectors.toMap(item -> item.getField(), item -> item.getDefaultMessage()));
        log.error(errorMap.toString());
        return HttpResult.error(SysExceptionEnum.VOLIDATION_ERROR.getCode(), errorMap.toString(), "");
    }
}
